package com.bdqn.common.utils;

import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

public class ResponseUitl {
    /**
     * 使用response输出JSON
     * @param servletResponse
     * @param result
     */
    public static void out(ServletResponse servletResponse, ServletRequest servletRequest, JSONObject result){

        PrintWriter out = null;
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setCharacterEncoding("UTF-8");
            String origin = request.getHeader("origin");
            if (StringUtils.isBlank(origin)) {
                origin = "*";
            }
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Expose-Headers", "Set-Cookie");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE");
            response.setHeader("Access-Control-Allow-Headers", "Accept, Origin, X-Requested-With, Content-Type, Last-Modified, accessToken");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(result.toJSONString());
            System.out.println(result.toJSONString());
        } catch (Exception e) {
//            log.error(e + "输出JSON出错");
        }finally{
            if(out!=null){
                out.flush();
                System.out.println("....out.flush()");
                out.close();
                System.out.println("....out.close()");
            }
        }
    }

    public static JSONObject result(Integer code, String msg){
        return result(code, msg, null);
    }

    public static JSONObject result(Integer code, String msg, Object data){
        JSONObject resultMap = new JSONObject();
        resultMap.put("status", code == 0);
        resultMap.put("msg", msg);
        resultMap.put("retmsg", msg);
        resultMap.put("code", code);
        resultMap.put("retcode", code);
        resultMap.put("data", data);
        return resultMap;
    }


    /**
     *
     * @param url  地址
     * @param headParamsMap
     * @param formMap  请求值
     * @param charset 编码
     * @return   list   0  数据   1  cookie
     */
    public static List<String> getCookieByDoPost(String url, Map<String, String> headParamsMap, Map<String, String> formMap, String charset) {
        CloseableHttpClient httpClient= null;
        HttpPost httpPost = null;
        StringBuffer cookie = new StringBuffer();

        try {

            CookieStore cookieStore = new BasicCookieStore();
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpPost = new HttpPost(url);

            if(formMap !=null){
                // 设置请求体参数
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator<Map.Entry<String, String>> iterator = formMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                    list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
                }
                if (list.size() > 0) {
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                    httpPost.setEntity(entity);
                }
            }

            // 设置请求头通用信息
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            if(headParamsMap !=null){
                Set<Map.Entry<String, String>> entrySet = headParamsMap.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {

                    httpPost.addHeader(entry.getKey()+"", entry.getValue()+"");
                }
            }

            HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity!=null){
                String result = EntityUtils.toString(entity,"UTF-8");
                if(null == result || "".equals(result)){
                    return null;
                }
                List<String> result_list=new ArrayList<>();

                List<Cookie> cookies = cookieStore.getCookies();
                if(cookies!=null && cookies.size()>0){
                    for (Cookie c : cookies) {
                        cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                    }
                }
                result_list.add(0,result);
                result_list.add(1,cookie.toString());

                return result_list;
            }
           /* if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    // 获得Cookies
                    List<Cookie> cookies = cookieStore.getCookies();
                    for (Cookie c : cookies) {
                        cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                        if (c.getName().equals("_tb_token_")) {
                           String tokenStr = c.getValue();
                        }
                    }
                }
            }*/
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            httpPost.abort();
        }
        return null;
    }
    public static  void main (String[] args) throws Exception {
        //  getToken();
    }

    public  static HashMap getByAuthorization(String url, Map<String, String> headParamsMap, Map<String, String> formMap, String charset) {
        CloseableHttpClient httpClient= null;
        HttpPost httpPost = null;
        StringBuffer cookie = new StringBuffer();

        try {

            CookieStore cookieStore = new BasicCookieStore();
            httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            httpPost = new HttpPost(url);

            if(formMap !=null){
                // 设置请求体参数
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator<Map.Entry<String, String>> iterator = formMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                    list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
                }
                if (list.size() > 0) {
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                    httpPost.setEntity(entity);
                }
            }

            // 设置请求头通用信息
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            if(headParamsMap !=null){
                Set<Map.Entry<String, String>> entrySet = headParamsMap.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            HttpResponse response = (HttpResponse) httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity!=null){
                String result = EntityUtils.toString(entity,"UTF-8");
                if(null == result || "".equals(result)){
                    return null;
                }
                return   JSON.parseObject(result,HashMap.class);

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            httpPost.abort();
        }
        return null;
    }
    public static String pullMessage(Object object,String key){
        if(null == object){
            return "请求超时";
        }
        JSONObject jResult = JSONObject.parseObject(object.toString());
        return jResult.getString(key);
    }
}
